#include <vector>
using namespace std;
/*
 * @lc app=leetcode.cn id=54 lang=cpp
 *
 * [54] 螺旋矩阵
 */

// @lc code=start
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int m = matrix.size(), n = matrix[0].size();
        vector<int> res;
        int i = 0, j = -1, c = 0;
        while (c <= (min(m, n)- 1) / 2) {
            if (j + 1 == n - c) break;
            while (++j < n - c) res.push_back(matrix[i][j]); j--;
            if (i + 1 == m - c) break;
            while (++i < m - c) res.push_back(matrix[i][j]); i--;
            if (j - 1 == c - 1) break;
            while (--j >= c) res.push_back(matrix[i][j]); j++;
            if (i - 1 == c) break;
            while (--i > c) res.push_back(matrix[i][j]); i++;
            c++;
        }
        return res;
    }
};
// @lc code=end

